package com.seventeen.service.impl;

import com.seventeen.common.Const;
import com.seventeen.common.ServerResponse;
import com.seventeen.common.TokenCache;
import com.seventeen.dao.UserMapper;
import com.seventeen.pojo.User;
import com.seventeen.service.IUserService;
import com.seventeen.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by geely
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public ServerResponse<User> login(String username, String password) {
       //检查登陆的用户名是否存在
        int i = userMapper.checkUsername(username);
        if(i<0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        //MD5对密码加密
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, md5Password); //检查用户名密码是否对
        if (user == null) {
            return ServerResponse.createByErrorMessage("密码错误");
        }

        //将用户密码置空
        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功", user);
    }

    public ServerResponse<String> register(User user) {
        //校验用户名是否存在
        ServerResponse<String> checkValid = this.check_valid(user.getUsername(), Const.USERNAME);
        if (!checkValid.isSuccess()) {  //如果不成功
            return checkValid;       //返回参数错误
        }

        checkValid = this.check_valid(user.getUsername(), Const.EMAIL);
        if (!checkValid.isSuccess()) {  //如果不成功
            return checkValid;       //返回参数错误
        }

        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败！");
        }
        return ServerResponse.createBySuccessMessage("注册成功！");
    }

    public ServerResponse<String> check_valid(String str, String type) {
        int resultCount = 0;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(type)) { //isNotBlank是否不为空
            //校验用户名是否存在
            if (Const.USERNAME.equals(type)) {
                resultCount = userMapper.checkUsername(str);//检查登陆的用户名是否已存在
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("用户名已存在"); //status = 1
                }
            }
            if (Const.EMAIL.equals(type)) {
                //校验Email是否存在
                resultCount = userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMessage("Email已存在");
                }
            }

        } else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");  //status = 0  用户名不存在

    }

    //查询问题是否存在 存在 返回问题
    public ServerResponse<String> selectQuestion(String username){
        // 1. 校验用户名是否存在
        ServerResponse<String> checkValid = this.check_valid(username, Const.USERNAME);
        if(checkValid.isSuccess()){  //status == 0用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        // 2. 查找问题
        String question = userMapper.selectQuestionByUsername(username);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(question)){ //isNotBlank排除空格作为参数
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    //检查问题答案是否正确  正确 --> 进入下一步重置密码
    public ServerResponse<String> checkAnswer(String username,String question,String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        if(resultCount>0){
            //说明问题及问题答案是这个用户的，并且是正确的
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");  //重新输入或者返回
    }

    //密码重置
    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        //判断forgetToken是否为空
        if(org.apache.commons.lang3.StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误，token需要传递");
        }
        //判断用户名是否存在
        ServerResponse<String> validResponse = this.check_valid(username, Const.USERNAME);
        if(validResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        //判断token是否为空
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if(org.apache.commons.lang3.StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }
        //判断token是否相等
        if(org.apache.commons.lang3.StringUtils.equals(forgetToken,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username, md5Password);
            if (rowCount>0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew,User user){
        //防止横向越权，校验一下指定用户的旧密码，如果不指定id,那么结果就是true
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if(resultCount==0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createBySuccessMessage("密码更新失败");
    }


    public ServerResponse<User> updateInformation(User user){
        //username不能被更新  Email也要进行验证，校验新的email是不是已经存在，并且存在的email如果相同的话不能是当前这个用户的
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if(resultCount>0){
            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试跟新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新个人信息成功",user);
        }
        return ServerResponse.createBySuccessMessage("更新个人信息失败");
    }

    public ServerResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }



    //=======backend

    //校验是否是管理员
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


}
